//
//  DataBaseManager.m
//  RetailConnect
//
//  Created by AonePOS on 24/09/13.
//  Copyright (c) 2013 AonePOS. All rights reserved.
//

#import "DataBaseManager.h"

static DataBaseManager *dataBaseManager = nil;

@implementation DataBaseManager
@synthesize rowCount,numberOfRows;
#pragma mark -
#pragma mark - DataBaseManager initialization
-(id) init
{
	self = [super init];
	if (self)
    {
		// get full path of database in documents directory
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *path = [paths objectAtIndex:0];
		_dataBasePath = [path stringByAppendingPathComponent:@"aoneposstar.sqlite"];
		////NSLog(@"DataBase : %@",_dataBasePath);
		_database = nil;
		[self openDatabase];
    }
	return self;
}

/*
 * open database
 * if database doesn't exist, create it
 *
 */
-(void)openDatabase
{
	BOOL ok;
	NSError *error;
	NSFileManager *fm = [NSFileManager defaultManager];
	ok = [fm fileExistsAtPath:_dataBasePath];
	if (!ok)
    {
        NSString *appPath = [[NSBundle mainBundle] pathForResource:@"aoneposstar" ofType:@"sqlite"];
        if ([fm fileExistsAtPath:appPath]) {
            copyDb = [fm copyItemAtPath:appPath toPath:_dataBasePath error:&error];
            if (error!=nil) {
                copyDb = FALSE;
            }
            ok = copyDb;
        }
        
    }
    
    
    // open database
    sqlite3_shutdown();
    sqlite3_config(SQLITE_CONFIG_SERIALIZED);
    sqlite3_initialize();
    if (sqlite3_open([_dataBasePath UTF8String], &_database) != SQLITE_OK)
    {
        sqlite3_close(_database); // in case partially opened
        _database = nil; // signal open error
    }
    if (!copyDb && !ok)
    { // first time and database not copied
        //ok = [self createDatabase]; // create empty database
        if (ok)
        {
            // Populating Table first time from the keys.plist
            /*	NSString *pListPath = [[NSBundle mainBundle] pathForResource:@"ads" ofType:@"plist"];
             NSArray *contents = [NSArray arrayWithContentsOfFile:pListPath];
             for (NSDictionary* dictionary in contents) {
             
             NSArray* keys = [dictionary allKeys];
             [self execute:[NSString stringWithFormat:@"insert into ads values('%@','%@','%@')",[dictionary objectForKey:[keys objectAtIndex:0]], [dictionary objectForKey:[keys objectAtIndex:1]],[dictionary objectForKey:[keys objectAtIndex:2]]]];
             }*/
        }
    }
    
    if (!ok)
    {
        // problems creating database
        NSAssert1(0, @"Problem creating database [%@]",[error localizedDescription]);
    }
    
}
-(BOOL) executeRecordsWithQuery:(NSString *) sqlQuery withArguments:(NSMutableArray *) values
{
  // NSLog(@"%@",values);
  // NSLog(@"%@",sqlQuery);
    BOOL status = YES;
    const char *sqliteString = [sqlQuery UTF8String];
    sqlite3_stmt *statement;
    if (sqlite3_prepare_v2(_database, sqliteString, -1, &statement, nil) == SQLITE_OK) {
        for (int i = 0; i<values.count; i++) {
            sqlite3_bind_text(statement, i+1, [[values objectAtIndex:i] UTF8String],-1, NULL);
        }
    }
    
    if (sqlite3_step(statement) != SQLITE_DONE){
        NSAssert(0, @"Error updating table.");
        status = NO;
    }
    sqlite3_finalize(statement);
    return status;
}
+(DataBaseManager*)dataBaseManager
{
	if(dataBaseManager==nil)
    {
		dataBaseManager = [[DataBaseManager alloc]init];
	}
	return dataBaseManager;
}
#pragma mark -
#pragma mark - Insert Query
/*
 * Method to execute the simple queries
 */
//-(BOOL)execute:(NSString*)sqlStatement
//{
//	sqlite3_stmt *statement = nil;
//    BOOL status = FALSE;
//    //	//NSLog(@"%@",sqlStatement);
//	const char *sql = (const char*)[sqlStatement UTF8String];
//    
//	
//	if(sqlite3_prepare_v2(_database, sql, -1, &statement, NULL) != SQLITE_OK) {
//        ////NSLog(@"Error while preparing  statement. '%s'", sqlite3_errmsg(_database));
//        ////NSLog(@"%@",sqlStatement);
//        status = FALSE;
//    } else {
//        status = TRUE;
//    }
//	if (sqlite3_step(statement)!=SQLITE_DONE) {
//        NSLog(@"Error while executing. '%s'", sqlite3_errmsg(_database));
//        NSLog(@"Error query:%@",sqlStatement);
//        status = FALSE;
//	}
//    else {
//        status = TRUE;
//	}
//	
//	sqlite3_finalize(statement);
//    return status;
//}

#pragma mark -
#pragma mark - SQL query methods
/*
 * Method to get the data table from the database
 */
-(BOOL) execute:(NSString*)sqlQuery resultsArray:(NSMutableArray*)dataTable
{
    
    
    char** azResult = NULL;
    int nRows = 0;
    int nColumns = 0;
    BOOL status = FALSE;
    char* errorMsg; //= malloc(255); // this is not required as sqlite do it itself
    const char* sql = [sqlQuery UTF8String];
    sqlite3_get_table(
                      _database,  /* An open database */
                      sql,     /* SQL to be evaluated */
                      &azResult,          /* Results of the query */
                      &nRows,                 /* Number of result rows written here */
                      &nColumns,              /* Number of result columns written here */
                      &errorMsg      /* Error msg written here */
                      );
	if (errorMsg) {
        //NSLog(@"error while executing --- %s",sqlite3_errmsg(_database));
        //NSLog(@"Error query:%@",sqlQuery);
    }
    if(azResult != NULL)
    {
        nRows++; //because the header row is not account for in nRows
		
        for (int i = 1; i < nRows; i++)
        {
            NSMutableDictionary* row = [[NSMutableDictionary alloc]initWithCapacity:nColumns];
            for(int j = 0; j < nColumns; j++)
            {
                NSString*  value = nil;
                NSString* key = [NSString stringWithUTF8String:azResult[j]];
                if (azResult[(i*nColumns)+j]==NULL)
                {
                    value = [NSString stringWithUTF8String:[[NSString string] UTF8String]];
                }
                else
                {
                    value = [NSString stringWithUTF8String:azResult[(i*nColumns)+j]];
                }
				
                [row setValue:value forKey:key];
            }
            [dataTable addObject:row];
        }
        status = TRUE;
        sqlite3_free_table(azResult);
    }
    else
    {
        NSLog(@"Failed to execute query with message '%s'.",errorMsg);
        NSLog(@"Error query:%@",sqlQuery);
        status = FALSE;
    }
    
    nRows=numberOfRows;
    rowCount=[[NSMutableArray alloc]init];
    self.rowCount=dataTable;
    if (dataTable.count>0) {
        status = TRUE;
    }
    else
        status = FALSE;
    
    return status;
}
/*
 * Method to get the integer value from the database
 */
-(void)dataBaseStatementStart
{
    sqlite3_exec(_database, "BEGIN EXCLUSIVE TRANSACTION", 0, 0, 0);
}
-(void)databasestatementEnd
{
    sqlite3_exec(_database, "COMMIT TRANSACTION", 0, 0, 0);
}

#pragma mark -
#pragma mark - Dealloc
-(void)dealloc
{
	sqlite3_close(_database);
    dataBaseManager = nil;
}
@end
